package xhttp

import (
	"gitee.com/cooge/impush/config"
	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	"gitee.com/cooge/impush/rest"
	"gitee.com/cooge/impush/xhttp/chttp"
	"gitee.com/cooge/impush/xhttp/ohttp"
	"gitee.com/cooge/impush/xhttp/user"
	"github.com/sirupsen/logrus"
	"net/http"
	"runtime"
	"time"
)

type HttpServer struct {
	cdr      user.CallDealRequestFunc
	cnc      user.CallNewConnFunc
	exchange ExChangeFunc
}

func Start() {
	go goScan()
	chs := NewCHttpServer()
	chs.Start()
}
func NewCHttpServer() *HttpServer {
	return &HttpServer{cdr: user.CallDealRequest, cnc: user.CallNewConn}
}
func (hs *HttpServer) Start() {
	if config.EX_MODEL == "C" {
		http.HandleFunc("/ex", hs.cexchange)
	} else {
		http.HandleFunc("/ex", hs.oexchange)
	}
	http.HandleFunc("/ex/sendmsg", rest.SendMessage)
}

type ExChangeFunc func(http.ResponseWriter, *http.Request)

func (hs *HttpServer) cexchange(w http.ResponseWriter, r *http.Request) {
	ok, nc, id := hs.cdr(w, r)
	if ok {
		ncc := chttp.NewCHttpConn(nc)
		ncc.Start(config.EX_DEADLINE, config.EX_LIVETIME, id, hs.cnc)
	}
}
func (hs *HttpServer) oexchange(w http.ResponseWriter, r *http.Request) {
	ok, nc, id := hs.cdr(w, r)
	if ok {
		ncc := ohttp.NewOHttpConn(nc)
		ncc.Start(config.EX_DEADLINE, config.EX_LIVETIME, id, hs.cnc)
	}
}

func goScan() {
	flush := config.EX_LIVETIME
	timer1 := time.NewTicker(time.Duration(flush) * time.Second)
	for {
		select {
		case <-timer1.C:
			{
				logrus.Debug("HTTP", "扫描用户防止过期")
				us := core.GetALLUsers()
				for num, vu := range us {
					ius := core.GetUser(vu)
					if ius!=nil{
						for _, v := range ius.GetAllArray() {
							if v.GetType() == message.HTTP {
								h, ok := v.(*user.HttpConn)
								if ok {
									h.Flush()
								}else{
									logrus.Debug("类型转换失败",vu)
								}
							}
						}
					}
					if num>>7<<7 == num {
						runtime.Gosched()
					}
				}
			}
		}
	}

}
